package cn.edu.zjut.mina.service.impl;

import org.apache.mina.core.session.IoSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import cn.edu.zjut.mina.bean.RoomInfo;
import cn.edu.zjut.mina.bean.StandardFormat;
import cn.edu.zjut.mina.po.UserInfo;
import cn.edu.zjut.mina.protocal.JMessageProtocalRes;
import cn.edu.zjut.mina.protocal.ProtocalRegulation;
import cn.edu.zjut.mina.service.IBackToRoomService;
import cn.edu.zjut.mina.service.INotificationService;
import cn.edu.zjut.mina.util.DateUtils;
import cn.edu.zjut.mina.util.GsonUtils;
import cn.edu.zjut.mina.util.UserMap;
import cn.edu.zjut.mina.util.UserSessionMap;
import cn.edu.zjut.mina.util.ResultInfoConstUtils;
@Service("backToRoomService")
public class BackToRoomServiceImpl implements IBackToRoomService{

	/**
	 * 用于存放用户信息的集合
	 */
	private final UserSessionMap userSessionMap = UserSessionMap.getInstance();
	
	/**
	 * 用于存放用户信息的集合
	 */
	private final UserMap userMap = UserMap.getInstance();
	
	@Qualifier("notificationService")
	@Autowired
	private INotificationService notificationService;
	
	public JMessageProtocalRes backToRoom(StandardFormat inJson,
			IoSession session) {
		// TODO Auto-generated method stub
		System.out.println(DateUtils.getTime() + "用户" + session.getAttribute("user") + "返回房间");
		JMessageProtocalRes res = new JMessageProtocalRes();
		StandardFormat outJson = new StandardFormat();
		String datas;
		UserInfo user = userMap.get(inJson.userId).user;
		if (user == null) {
			System.out.println(DateUtils.getTime() + "用户" + session.getAttribute("user") + "返回房间：用户为空");
			outJson.userId = inJson.userId;
			outJson.result = false;
			outJson.resultInfo = ResultInfoConstUtils.BACKTOROOM_USERNULLINFO;
    	} else {
    		String roomId = user.getRoomId();
    		if (roomId == null) {
    			System.out.println(DateUtils.getTime() + "用户" + session.getAttribute("user") + "返回房间：房间号");
    			outJson.userId = inJson.userId;
    			outJson.result = false;
    			outJson.resultInfo = ResultInfoConstUtils.BACKTOROOM_ROOMNULLINFO;
    		} else {
    			//连接
    			user.setLostConnection(0);
    			//通知所有人，房主已经返回房间
    			notificationService.notificationBackToRoom(roomId, inJson.userId);
    			return null;
    		}
    	}
		
		//异常信息返回
		res.setResultCode(ProtocalRegulation.PREPAREINITIATIVE);
		datas = GsonUtils.beanToJson(outJson).trim();
		res.setContent(datas);
		return res;
	}

}
